import { animation, AnimationClip, Sprite, SpriteFrame } from "cc";
import ResourcesManager from "../Runtime/ResourceManager";
import { StateMachine } from "./StateMachine";
import { sortSpriteFrame } from "../Scripts/Utils";

export const ANIMATION_SPEED = 1 / 8

export default class State {
    private animationClip: AnimationClip;

    constructor(
        private fsm: StateMachine,
        private path: string,
        private warpMode: AnimationClip.WrapMode = AnimationClip.WrapMode.Normal,
        private speed: number = ANIMATION_SPEED,
        private events: any[] = [] // 高版本废弃了教程中的方法，暂时还不会使用其他方法来实现
    ) {
        this.init();
    };

    async init() {


        const promise = ResourcesManager.Instance.loadRes(this.path);
        this.fsm.waitingList.push(promise);
        const spriteFrames = await promise
        this.animationClip = new AnimationClip();


        const track = new animation.ObjectTrack();
        track.path = new animation.TrackPath().toComponent(Sprite).toProperty('spriteFrame');
        const frames: Array<[number, SpriteFrame]> = sortSpriteFrame(spriteFrames).map((item: SpriteFrame, index: number) => [this.speed * index, item]);
        track.channel.curve.assignSorted(frames);

        //最后将轨道添加到动画剪辑以应用
        this.animationClip.addTrack(track);
        this.animationClip.name = this.path;
        this.animationClip.duration = frames.length * this.speed;
        this.animationClip.wrapMode = this.warpMode;

        // let event = new AnimationEvent('');
        // for (event of this.events) {
        //     this.animationClip.events.push(event);

        // }


    }
    run() {
        if (this.fsm.animationComponent?.defaultClip?.name === this.animationClip.name) {
            return;
        }
        this.fsm.animationComponent.defaultClip = this.animationClip;
        this.fsm.animationComponent.play();
    }

}